"use client";

import React, { useState, useEffect } from "react";
import {
	Form,
	Input,
	Select,
	DatePicker,
	Button,
	message,
	Space,
	Typography,
	Divider
} from "antd";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import { createRecruitmentPlan } from "@/lib/recruitment";
import { getAllDepartments } from "@/lib/departments";
import { getAcademyList } from "@/lib/academy";
import { getAllOtherDepartments } from "@/lib/otherdept";
import { fetchEmployeeData } from "@/lib/user";
import { useRouter } from "next/navigation";

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface CreatePlanFormProps {
	employeeOptions: Array<{
		value: string;
		label: string;
		department: string;
	}>;
	initialValues?: any; // 添加 initialValues 属性
	onCancel: () => void;
	onSuccess: () => void;
}

// 修改 employees 的数据结构类型定义
interface Employee {
  value: string;
  label: string;
  department: string;
  phoneNumber: string | null;
}

// 2. 在组件参数中添加 initialValues
const CreatePlanForm: React.FC<CreatePlanFormProps> = ({
	employeeOptions,
	initialValues = null, // 添加默认值为 null
	onCancel,
	onSuccess
}) => {
	console.log("CreatePlanForm 组件被渲染", { onCancel, onSuccess });
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [planType, setPlanType] = useState(1);
	const [deptOptions, setDeptOptions] = useState<any[]>([]);
	const [employees, setEmployees] = useState<Employee[]>([]);
	const router = useRouter();

	// 获取员工数据
	useEffect(() => {
		const loadEmployees = async () => {
			try {
				const response = await fetchEmployeeData({});
				if (response.data && response.data.code === 1) {
					// 确保我们使用正确的数据结构访问员工列表
					const employeeList = response.data.data.row.map((emp: any) => ({
						value: emp.employeeId,
						label: `${emp.employeeId} - ${emp.username}`,
						department: emp.deptName,
						phoneNumber: emp.phoneNumber // 添加电话号码
					}));
					setEmployees(employeeList);
				} else {
					message.error(response.data?.msg || "获取员工数据失败");
				}
			} catch (error: any) {
				console.error("获取员工数据失败:", error);
				message.error("获取员工数据失败");
			}
		};
		loadEmployees();
	}, []);
	// 编辑时回显初始数据（注意初始数据中的 depts 数组应包含用人部门与岗位数据等）
	useEffect(() => {
		if (initialValues) {
			form.setFieldsValue({
				...initialValues,
				startDate: dayjs(initialValues.startDate),
				endDate: dayjs(initialValues.endDate),
				publishDate: dayjs(initialValues.publishDate)
			});
			if (initialValues.planType) {
				setPlanType(initialValues.planType);
			}
		}
	}, [initialValues, form]);

	const fetchAvailableDepts = async (selectedPlanType: number) => {
		try {
			setDeptOptions([]); // 先清空现有数据
			
			if (selectedPlanType === 1) { // 管理岗位 - 获取职能部门
				// 调用职能部门API: /department
				console.log('获取职能部门数据，调用/department接口');
				const response = await getAllDepartments();
				console.log('获取到的职能部门数据:', response); // 打印部门数据
				
				if (response.data.code === 1) {
					// 检查数据是否符合职能部门格式
					if (!Array.isArray(response.data.data)) {
						console.error("职能部门数据格式错误，不是数组:", response.data.data);
						setDeptOptions([]);
						return;
					}
					
					setDeptOptions(response.data.data);
				} else {
					message.error(response.data.msg || "获取职能部门数据失败");
					setDeptOptions([]);
				}
			} else if (selectedPlanType === 2) { // 专任教师 - 获取二级学院
				// 调用学院API: /department/academy
				console.log('获取二级学院数据，调用/department/academy接口');
				const response = await getAcademyList();
				console.log('获取到的二级学院原始数据:', response); // 打印学院数据
				
				// 学院API响应结构直接返回数组
				if (Array.isArray(response)) {
					console.log('学院数据是数组，包含', response.length, '个学院');
					// 学院数据可能格式不同，打印第一个元素结构
					if (response.length > 0) {
						console.log('第一个学院数据样例:', response[0]);
					}
					
					setDeptOptions(response);
				} else {
					console.error("获取学院数据格式错误:", response);
					message.error("获取二级学院数据格式不正确");
					setDeptOptions([]);
				}
			} else if (selectedPlanType === 3) { // 其他岗位 - 获取其他部门
				// 调用其他部门API: /department/otherDept
				console.log('获取其他部门数据，调用/department/otherDept接口');
				const response = await getAllOtherDepartments();
				console.log('获取到的其他部门数据:', response); // 打印其他部门数据
				
				// 对于其他岗位类型，不需要显示错误信息，因为该类型不需要选择部门
				if (response.data.code === 1) {
					if (!Array.isArray(response.data.data)) {
						console.error("其他部门数据格式错误，不是数组:", response.data.data);
						setDeptOptions([]);
						return;
					}
					
					setDeptOptions(response.data.data);
				} else {
					console.log('其他部门数据获取结果：', response.data.msg);
					setDeptOptions([]);
				}
			}
		} catch (error: any) {
			console.error("获取部门数据失败:", error);
			// 对于其他岗位类型，不显示错误信息
			if (selectedPlanType !== 3) {
				message.error("获取部门数据失败");
			} else {
				console.error("获取其他部门数据失败:", error);
			}
			setDeptOptions([]);
		}
	};
	
	useEffect(() => {
		fetchAvailableDepts(planType);
	}, [planType]);

	//处理选择不同招聘类型
	const handlePlanTypeChange = (value: number) => {
		setPlanType(value);
		form.resetFields(["depts"]);
		fetchAvailableDepts(value);
	};

	//提交表单
	const handleSubmit = async (values: any) => {
		console.log("表单提交开始");
		setLoading(true);
		try {
		  const currentDate = dayjs().format("YYYY-MM-DD");
		  const formattedValues = {
			...values,
			startDate: values.startDate.format("YYYY-MM-DD"),
			endDate: values.endDate.format("YYYY-MM-DD"),
			publishDate: currentDate,
			recruitmentConditions: values.planType === 3 ? "" : values.recruitmentConditions,
			benefitsDescription: values.planType === 3 ? "" : values.benefitsDescription,
			interviewProcess: values.planType === 3 ? "" : values.interviewProcess,
			recruiterId: values.recruiter,
			recruiter: undefined,
			depts: values.depts?.map((dept: any) => ({
			  ...dept,
			  numbering: dept.deptSelect // 添加部门编号
			}))
		  };
	  
		  console.log("最终提交的数据:", formattedValues);
		  
		  // 验证日期
		  if (values.endDate.isBefore(values.startDate)) {
			message.error("结束日期不能早于开始日期");
			setLoading(false);
			return;
		  }
	  
		  // 验证部门和岗位信息
		  if (formattedValues.planType === 3) {
			delete formattedValues.depts;
		  } else {
			// 验证部门和岗位信息
			if (!formattedValues.depts?.length) {
			  message.error("请至少添加一个用人部门");
			  setLoading(false);
			  return;
			}
			for (const dept of formattedValues.depts) {
			  if (!dept.positions?.length) {
				message.error(`部门 ${dept.deptSelect} 需要至少添加一个岗位`);
				setLoading(false);
				return;
			  }
			}
		  }

		  console.log("调用API创建招聘计划", formattedValues);
		  const response = await createRecruitmentPlan(formattedValues);
		  console.log("创建招聘计划结果:", response);
		  message.success("创建招聘计划成功");
		  
		  // 确保在异步操作完成后再调用回调
		  setTimeout(() => {
			  console.log("准备调用onSuccess回调", onSuccess);
			  if (onSuccess) {
				console.log("调用onSuccess回调");
				onSuccess();
				console.log("onSuccess回调结束");
			  } else {
				console.log("onSuccess回调不存在");
				// 如果没有回调，直接返回列表页
				router.push('/recruitment/plan');
			  }
		  }, 0);
		  
		} catch (error: any) {
		  console.error("创建招聘计划失败:", error);
		  message.error(error.message || "创建招聘计划失败");
		} finally {
		  setLoading(false);
		  console.log("表单提交结束");
		}
	  };

	return (
		<div style={{ padding: "24px" }}>
			<Title level={2}>新增招聘计划</Title>
			<Form
				form={form}
				layout="vertical"
				onFinish={handleSubmit}
				initialValues={{ approveStatus: 0, planType: 1 }}
			>
				{/* 基本信息 */}
				<Title level={4}>基本信息</Title>
				<Form.Item
					name="planName"
					label="计划名称"
					rules={[{ required: true, message: "请输入计划名称" }]}
				>
					<Input placeholder="请输入计划名称" />
				</Form.Item>
				<Form.Item
					name="planCode"
					label="计划编号"
					rules={[{ required: true, message: "请输入计划编号" }]}
				>
					<Input placeholder="请输入计划编号" />
				</Form.Item>
				<Form.Item
					name="planType"
					label="计划类型"
					rules={[{ required: true, message: "请选择计划类型" }]}
				>
					<Select onChange={handlePlanTypeChange}>
						<Option value={1}>管理岗位</Option>
						<Option value={2}>专任教师</Option>
						<Option value={3}>其他岗位</Option>
					</Select>
				</Form.Item>

				{/* 时间信息 */}
				<Title level={4}>时间信息</Title>
				<Form.Item
				name="startDate"
				label="开始日期"
				rules={[{ required: true, message: "请选择开始日期" }]}
				>
				<DatePicker style={{ width: "100%" }} />
				</Form.Item>

				<Form.Item
				name="endDate"
				label="结束日期"
				rules={[
					{ required: true, message: "请选择结束日期" },
					({ getFieldValue }) => ({
					validator(_, value) {
						if (!value || !getFieldValue('startDate') || value.isAfter(getFieldValue('startDate'))) {
						return Promise.resolve();
						}
						return Promise.reject(new Error('结束日期不能早于开始日期'));
					},
					}),
				]}
				>
				<DatePicker style={{ width: "100%" }} />
				</Form.Item>

				{/* 审批信息 */}
				{/* 移除审批信息部分
				<Title level={4}>审批信息</Title>
				<Form.Item
					name="approver"
					label="审批人"
					rules={[{ required: false, message: '请选择审批人' }]}
				>
					<Select
						placeholder="请选择审批人"
						showSearch
						optionFilterProp="children"
					>
						{Array.isArray(employees) && employees.map(emp => (
							<Option key={emp.value} value={emp.value}>
								{emp.label} - {emp.department}
							</Option>
						))}
					</Select>
				</Form.Item>
				*/}

				{planType !== 3 && (
				<>
					<Title level={4}>招聘负责人信息</Title>
					<Form.Item
					name="recruiter"
					label="招聘负责人"
					rules={[{ required: true, message: '请选择招聘负责人' }]}
					>
					<Select
						placeholder="请选择招聘负责人"
						showSearch
						optionFilterProp="children"
						onChange={(value) => {
							const selectedEmployee = employees.find(emp => emp.value === value);
							if (selectedEmployee) {
								form.setFieldsValue({
									recruiterName: selectedEmployee.label.split(' - ')[1],
									recruiterPhone: selectedEmployee.phoneNumber || '暂无电话号码' // 添加电话号码回填
								});
							}
						}}
					>
						{Array.isArray(employees) && employees.map(emp => (
							<Option key={emp.value} value={emp.value}>
								{emp.label} - {emp.department}
							</Option>
						))}
					</Select>
					</Form.Item>
					<Form.Item name="recruiterName" label="招聘负责人姓名">
					<Input readOnly placeholder="自动回填招聘负责人姓名" />
					</Form.Item>
					<Form.Item name="recruiterPhone" label="招聘负责人电话">
					<Input readOnly placeholder="自动回填招聘负责人电话" />
					</Form.Item>
					<Form.Item
					name="recruitmentConditions"
					label="招聘条件"
					rules={[{ required: true, message: "请输入招聘条件" }]}
					>
					<TextArea rows={3} placeholder="请输入招聘条件" />
					</Form.Item>
					<Form.Item
					name="benefitsDescription"
					label="待遇说明"
					rules={[{ required: true, message: "请输入待遇说明" }]}
					>
					<TextArea rows={3} placeholder="请输入待遇说明" />
					</Form.Item>
					<Form.Item
					name="interviewProcess"
					label="面试流程描述"
					rules={[{ required: true, message: "请输入面试流程描述" }]}
					>
					<Input.TextArea rows={3} placeholder="请输入面试或招聘流程描述" />
					</Form.Item>
				</>
				)}

				{/* 当计划类型为其他岗位时，公告内容为必填 */}
				{planType === 3 && (
					<>
						<Form.Item
							name="content"
							label="公告内容"
							rules={[{ required: true, message: "请输入公告内容" }]}
						>
							<Input.TextArea rows={4} placeholder="请输入公告内容" />
						</Form.Item>
						<div style={{ background: '#f0f9ff', padding: '10px 16px', marginBottom: '20px', borderRadius: '4px', color: '#1677ff' }}>
							注意：其他岗位类型不需要选择部门和岗位信息，直接填写公告内容即可。
						</div>
					</>
				)}

				{/* 用人部门及岗位信息，仅当计划类型不为其他岗位时展示 */}
				{planType !== 3 && (
					<>
						<Title level={4}>用人部门信息</Title>
						<div style={{ background: '#e6f7ff', padding: '10px 16px', marginBottom: '20px', borderRadius: '4px', color: '#1677ff' }}>
							<strong>提示：</strong> 
							{planType === 1 
								? "管理岗位招聘计划只能选择职能部门" 
								: "专任教师招聘计划只能选择二级学院"}
						</div>
						<Form.List name="depts">
							{(fields, { add, remove }) => (
								<>
									{fields.map((field, deptIndex) => (
										<div key={field.key}>
											<Divider orientation="left">{`部门 ${deptIndex + 1}`}</Divider>
											{/* 选择部门 */}
											<Form.Item
												{...field}
												name={[field.name, "deptSelect"]}
												label={planType === 1 ? "选择职能部门" : "选择二级学院"}
												rules={[{ required: true, message: planType === 1 ? "请选择职能部门" : "请选择二级学院" }]}
											>
												<Select placeholder={planType === 1 ? "请选择职能部门" : "请选择二级学院"}>
												{deptOptions.map((dept: any) => {
													const valueField = planType === 2 ? dept.academyNumber : dept.deptNumber;
													const nameField = planType === 2 ? dept.academyName : dept.deptName;
													const displayText = planType === 2 
													? `${dept.academyNumber} - ${dept.academyName}`
													: `${dept.deptNumber} - ${dept.deptName}`;
													
													return (
													<Option key={valueField} value={valueField}>
														{displayText}
													</Option>
													);
												})}
												</Select>
											</Form.Item>
											{/* 岗位信息 */}
											<Form.List name={[field.name, "positions"]}>
												{(posFields, { add: addPos, remove: removePos }) => (
													<>
														{posFields.map((posField, posIndex) => (
															<div
																key={posField.key}
																style={{ marginBottom: 8, padding: 8, border: "1px solid #ccc" }}
															>
																<Form.Item
																	{...posField}
																	name={[posField.name, "positionId"]}
																	label="岗位选择"
																	rules={[{ required: true, message: "请选择岗位" }]}
																>
																	<Select
																		placeholder="请选择岗位"
																		onChange={(value: string) => {
																			const selectedDept = deptOptions.find((d: any) => 
																			  planType === 2 
																				? d.academyNumber === form.getFieldValue(["depts", deptIndex, "deptSelect"])
																				: d.deptNumber === form.getFieldValue(["depts", deptIndex, "deptSelect"])
																			);
																			
																			const selectedJob = selectedDept?.positions?.find((job: any) => job.positionId === value);
																			if (selectedJob) {
																			  form.setFields([
																				{
																				  name: ["depts", deptIndex, "positions", posField.name, "positionNumber"],
																				  value: selectedJob.positionNumber
																				},
																				{
																				  name: ["depts", deptIndex, "positions", posField.name, "positionName"],
																				  value: selectedJob.positionName
																				}
																			  ]);
																			}
																		  }}
																	>
																		{(deptOptions
																			.find((d: any) => {
																				const deptValue = form.getFieldValue(["depts", deptIndex, "deptSelect"]);
																				return planType === 2 
																				? d.academyNumber === deptValue
																				: d.deptNumber === deptValue
																			})
																			?.positions || [])
																			.filter((job: any) => {
																				// 根据招聘计划类型筛选岗位
																				// 管理岗位招聘计划(planType=1)应该只显示职能部门类型(deptType=1)的岗位
																				// 专任教师招聘计划(planType=2)应该只显示二级学院类型(deptType=2)的岗位
																				return (planType === 1 && job.deptType === 1) || 
																					  (planType === 2 && job.deptType === 2);
																			})
																			.map((job: any) => (
																				<Option key={job.positionId} value={job.positionId}>
																				{`${job.positionNumber} - ${job.positionName}`}
																				</Option>
																		))}
																	</Select>
																</Form.Item>
																{/* 自动回填岗位编号和岗位名称 */}
																<Form.Item
																	{...posField}
																	name={[posField.name, "positionNumber"]}
																	label="岗位编号"
																>
																	<Input readOnly placeholder="自动回填岗位编号" />
																</Form.Item>
																<Form.Item
																	{...posField}
																	name={[posField.name, "positionName"]}
																	label="岗位名称"
																>
																	<Input readOnly placeholder="自动回填岗位名称" />
																</Form.Item>
																{/* 管理岗位需要填写岗位性质 */}
																{planType === 1 && (
																<Form.Item
																	{...posField}
																	name={[posField.name, "positionProperties"]}
																	label="岗位性质"
																	rules={[{ required: true, message: "请输入岗位性质" }]}
																>
																	<Input placeholder="请输入岗位性质" />
																</Form.Item>
																)}
																<Form.Item
																	{...posField}
																	name={[posField.name, "jobDescription"]}
																	label="岗位描述"
																	rules={[{ required: true, message: "请输入岗位描述" }]}
																>
																	<Input.TextArea placeholder="请输入岗位描述" rows={3} />
																</Form.Item>
																<Form.Item
																	{...posField}
																	name={[posField.name, "jobRequired"]}
																	label="任职要求"
																	rules={[{ required: true, message: "请输入任职要求" }]}
																>
																	<Input.TextArea placeholder="请输入任职要求" rows={3} />
																</Form.Item>
																<Form.Item
																	{...posField}
																	name={[posField.name, "person"]}
																	label="招聘人数"
																	rules={[{ required: true, message: "请输入招聘人数" }]}
																>
																	<Input type="number" placeholder="请输入招聘人数" />
																</Form.Item>
																{/* 新增岗位能力三个字段 */}
																<Form.Item
																	{...posField}
																	name={[posField.name, "professionalSkillsRight"]}
																	label="专业技能的权"
																	rules={[{ required: true, message: "请输入专业技能的权" }]}
																>
																	<Input type="number" placeholder="请输入专业技能的权" />
																</Form.Item>
																<Form.Item
																	{...posField}
																	name={[posField.name, "communicationSkillsRight"]}
																	label="沟通能力的权"
																	rules={[{ required: true, message: "请输入沟通能力的权" }]}
																>
																	<Input type="number" placeholder="请输入沟通能力的权" />
																</Form.Item>
																<Form.Item
																	{...posField}
																	name={[posField.name, "teamworkAbilityRight"]}
																	label="团队协作的权"
																	rules={[{ required: true, message: "请输入团队协作的权" }]}
																>
																	<Input type="number" placeholder="请输入团队协作的权" />
																</Form.Item>
																<Button type="link" danger onClick={() => removePos(posField.name)}>
																	删除岗位
																</Button>
															</div>
														))}
														<Form.Item>
															<Button type="dashed" onClick={() => addPos()} block icon={<PlusOutlined />}>
																添加岗位
															</Button>
														</Form.Item>
													</>
												)}
											</Form.List>
											<Button type="link" onClick={() => remove(field.name)} icon={<MinusCircleOutlined />}>
												删除部门
											</Button>
										</div>
									))}
									<Form.Item>
										<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
											添加部门
										</Button>
									</Form.Item>
								</>
							)}
						</Form.List>
					</>
				)}

				{/* 备注信息 */}
				<Title level={4}>备注信息</Title>
				<Form.Item name="notes" label="备注说明">
					<TextArea rows={4} placeholder="请输入备注说明（选填）" />
				</Form.Item>
				<Space style={{ marginTop: 16 }}>
					<Button onClick={() => {
						console.log("点击取消按钮");
						console.log("通过postMessage通知关闭模态框");
						window.postMessage({ type: 'CLOSE_CREATE_MODAL', reload: false }, '*');
						console.log("onCancel存在:", !!onCancel);
						if (onCancel) {
							console.log("调用onCancel");
							onCancel();
							console.log("onCancel调用结束");
						} else {
							console.log("onCancel不存在");
						}
					}}>取消</Button>
					<Button type="primary" htmlType="submit" loading={loading}>
						创建
					</Button>
				</Space>
			</Form>
		</div>
	);
};

// 修改导出方式
export default function Page({ onCancel, onSuccess }: { onCancel?: () => void, onSuccess?: () => void } = {}) {
	console.log("Page组件被渲染", { onCancel, onSuccess });
	const [employeeOptions, setEmployeeOptions] = useState<Array<{
		value: string;
		label: string;
		department: string;
	}>>([]);
	const router = useRouter();

	useEffect(() => {
		const fetchEmployees = async () => {
			try {
				const response = await fetchEmployeeData({ page: 1, pageSize: 100 });
				if (response.data && response.data.code === 1) {
					const employees = response.data.data.row || [];
					setEmployeeOptions(
						employees.map((emp: any) => ({
							value: emp.employeeId,
							label: `${emp.username} (${emp.employeeId})`,
							department: emp.deptName
						}))
					);
				}
			} catch (error) {
				console.error('获取员工列表失败:', error);
			}
		};

		fetchEmployees();
	}, []);

	const handleCancel = () => {
		console.log("Page组件的handleCancel被调用");
		// 如果传入了回调，直接调用
		if (onCancel) {
			onCancel();
		} else {
			// 如果没有回调，返回列表页
			router.push('/recruitment/plan');
		}
	};

	const handleSuccess = () => {
		console.log("Page组件的handleSuccess被调用");
		// 如果传入了回调，直接调用
		if (onSuccess) {
			onSuccess();
		} else {
			// 如果没有回调，返回列表页
			router.push('/recruitment/plan');
		}
	};

	return (
		<CreatePlanForm
			employeeOptions={employeeOptions}
			onCancel={handleCancel}
			onSuccess={handleSuccess}
		/>
	);
}